package com.qdxht.dispenser.utils;

import android.serialport.SerialPort;
import android.serialport.SerialPortFinder;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import com.hjq.toast.ToastUtils;
import com.vi.vioserial.COMSerial;
import com.vi.vioserial.NormalSerial;
import com.vi.vioserial.listener.OnComDataListener;

import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;

public class SerialPortFind {

    private static final String TAG = "SerialPortTest";

    private List<String> getSerialPortList() {
        List<String> list = new ArrayList<>();
        // 查找设备所有串口
        SerialPortFinder serialPortFinder = new SerialPortFinder();
        String[] allDevicesPath = serialPortFinder.getAllDevicesPath();
        if (allDevicesPath != null && allDevicesPath.length > 0) {
            for (String path : allDevicesPath) {
                if(path.contains("ttyS")){
                    list.add(path);
                }
            }
        }
        return list;
    }

    public String getSerialPort() {
        Timber.tag(TAG).i("getSerialPort");
        //需要在打开串口前调用
        SerialPort.setSuPath("/system/xbin/su");
        final String[] port = {null};
        COMSerial.instance().addDataListener(new OnComDataListener() {
            @Override
            public void comDataBack(String com, String hexData) {
                port[0] = com;
                ToastUtils.show("串口："+com +" "+hexData);
                Timber.tag(TAG).i("串口："+com +" "+hexData);
            }
        });
        // 发送命令获取剩余袋子测试命令
        String data = SerialProtocolUtil.buildFrame(0,SerialProtocolUtil.CMD_READ_CONFIG,05,"");
        Timber.tag(TAG).i("发送命令："+data);
        List<String> list = getSerialPortList();
        for (String path : list) {
            Timber.tag(TAG).i("path："+path);
            if(!path.contains("ttyS")){
                continue;
            }
            ToastUtils.show("找到串口："+path);
            Timber.tag(TAG).i("找到串口："+path);
            int openStatus = COMSerial.instance().addCOM(path, 9600);
            Timber.tag(TAG).i("打开状态："+openStatus);
            if(openStatus == 0){
                COMSerial.instance().sendHex(path, data);
                Timber.tag(TAG).i("发送命令："+data);
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        for (String path : list) {
//            if(COMSerial.instance().isOpen(path)){
//                COMSerial.instance().close(path);
//            }
//        }
        Timber.tag(TAG).i("找到端口："+port[0]);
        return port[0];
    }

}
